import React, { PureComponent } from 'react';
import { Menu, Icon, Spin, Tag, Dropdown, Avatar, Divider, Badge } from 'antd';
import moment from 'moment';
import { connect } from 'dva';
import groupBy from 'lodash/groupBy';
import Debounce from 'lodash-decorators/debounce';
import { Link, routerRedux } from 'dva/router';
import NoticeIcon from '../NoticeIcon';
import HeaderSearch from '../HeaderSearch';
import styles from './index.less';

@connect(({ global }) => ({
  global
}))
export default class GlobalHeader extends PureComponent {
  componentWillUnmount() {
    this.triggerResizeEvent.cancel();
  }

  getNoticeData() {
    // const { notices = [] } = this.props;
    // if (notices.length === 0) {
    //   return {};
    // }
    const { global: { notices } } = this.props;
    const newNotices = notices && notices.map(notice => {
      const newNotice = { ...notice };
      if (newNotice.id) {
        newNotice.key = newNotice.id;
      }
      return newNotice;
    });
    return groupBy(newNotices, 'type');
  }

  toggle = () => {
    const { collapsed, onCollapse } = this.props;

    onCollapse(!collapsed);
    this.triggerResizeEvent();
  };
  /* eslint-disable*/
  @Debounce(600)
  triggerResizeEvent() {
    const event = document.createEvent('HTMLEvents');
    event.initEvent('resize', true, false);
    window.dispatchEvent(event);
  }

  handleNoticeItemClick = (item, tabProps) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'global/getNoticesById',
      payload: {
        id: item.id
      },
      callback: () => {
        dispatch({
          type: 'global/fetchNotices',
        });
        // dispatch({
        //   type: 'global/updateMessageRead',
        //   payload: {
        //     item
        //   }
        // });
      }
    });
  }

  render() {
    const {
      currentUser = {},
      collapsed,
      fetchingNotices,
      isMobile,
      logo,
      onNoticeVisibleChange,
      onMenuClick,
      onNoticeClear,
      onNoticeAll,
    } = this.props;
    const { global: { sysTotal, applyTotal } } = this.props;
    const menu = (
      <Menu className={styles.menu} selectedKeys={[]} onClick={onMenuClick}>

        <Menu.Item key="updataPassword">
          <Icon type="lock" />修改密码
        </Menu.Item>
        <Menu.Divider />
        <Menu.Item key="logout">
          <Icon type="logout" />退出登录
        </Menu.Item>
      </Menu>
    );
    const noticeData = this.getNoticeData();

    return (
      <div className={styles.header}>
        {isMobile && [
          <Link to="/" className={styles.logo} key="logo">
            <img src={logo} alt="logo" width="32" />
          </Link>,
          <Divider type="vertical" key="line" />,
        ]}
        <Icon
          className={styles.trigger}
          type={collapsed ? 'menu-unfold' : 'menu-fold'}
          onClick={this.toggle}
        />
        <div className={styles.right}>
          {
            <NoticeIcon
              sysTotal={sysTotal}
              applyTotal={applyTotal}
              className={styles.action}
              count={currentUser.notifyCount}
              onItemClick={(item, tabProps) => {
                this.handleNoticeItemClick(item, tabProps)
              }}
              onAll={onNoticeAll}
              onPopupVisibleChange={onNoticeVisibleChange}
              loading={fetchingNotices}
              popupAlign={{ offset: [20, -16] }}
            >

              <NoticeIcon.Tab
                list={noticeData['通知']}
                title="通知"
                emptyText="你已查看所有通知"
                emptyImage="https://gw.alipayobjects.com/zos/rmsportal/wAhyIChODzsoKIOBHcBk.svg"
              />

              <NoticeIcon.Tab
                list={noticeData['待办']}
                title="待办"
                emptyText="你已完成所有待办"
                emptyImage="https://gw.alipayobjects.com/zos/rmsportal/HsIsxMZiWKrNUavQUXqx.svg"
              />
            </NoticeIcon>
          }
          {/* {currentUser.name ? ( */}
          <Dropdown overlay={menu}>
            <span className={`${styles.action} ${styles.account}`}>
              <Avatar size="small" className={styles.avatar} src={currentUser.avatar} />
              <span className={styles.name}>{sessionStorage.getItem("name")}</span>
            </span>
          </Dropdown>
          {/* ) : (
            <Spin size="small" style={{ marginLeft: 8 }} />
          )} */}
        </div>
      </div>
    );
  }
}
